﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.ServiceModel;
using System.Text;
using StudioLib;
namespace StudServ
{
    public class StudioSrv : IStudioSrv
    {
        List<String> files = new List<string>();

        public void Init()
        {
            files = new List<string>(Directory.GetFiles(".","*.std")); // ???
        }

        public bool UploadStudio(Studio std)
        {
            if (!std.CheckKey()) return false;

            //TODO: UPD TimeStamp check
            int id = files.FindIndex(delegate(string n)
                { return n == std.Name; });
            if (id != -1)
            {
                Studio old = Studio.FromFile(std.Name + ".std");
                if (old.Stamp <= std.Stamp)
                {
                    return false;
                }
            }

            std.SaveToFile(std.Name + ".std");

            return true;
        }

        public bool UpdateStudioReserve(string name, int key, 
            StudioLib.ReserveTable table)
        {
            if (!Studio.CheckKeyEx(name, key)) return false;

            Studio temp = Studio.FromFile(name + ".std");
            temp.Reservetable = table;
            temp.SaveToFile(name + ".std");

            return true;
        }

        public bool RemoveStudio(string name, int key)
        {
            if (!files.Exists(delegate(string n)
                { return n == name; }))
                return false;

            if (!Studio.CheckKeyEx(name,key))
                return false;

            File.Delete(name + ".std");
            files.Remove(name + ".std");

            return true;
        }

        public Studio GetStudio(string name)
        {
            return Studio.FromFile(name + ".std");
        }

        public List<string> GetStudios()
        {
            List<string> result = new List<string>(files);

            for (int i = 0; i < result.Count; i++)
            {
                result[i] = result[i].Substring(1, result[i].Length - 4);
            }

            return result;
        }


    }
        

        
    
}
